import { get, map } from "lodash";
import React, { useMemo, useCallback } from "react";
import PropTypes from "prop-types";
import { UserProfile } from "@/components/proptypes";
import DynamicComponent from "@/components/DynamicComponent";
import DynamicForm from "@/components/dynamic-form/DynamicForm";
import UserGroups from "@/components/UserGroups";

import User from "@/services/user";
import { currentUser } from "@/services/auth";
import useImmutableCallback from "@/lib/hooks/useImmutableCallback";

import useUserGroups from "../hooks/useUserGroups";

export default function UserInfoForm(props) {
  const { user, onChange } = props;

  const { groups, allGroups, isLoadingGroups, orgunits, isLoadingOrgunits, menustyle_enums, isLoadingMenustyle } = useUserGroups(user);

  const handleChange = useImmutableCallback(onChange);

  const saveUser = useCallback(
    (values, successCallback, errorCallback) => {
      const data = {
        ...values,
        id: user.id,
      };

      User.save(data)
        .then(user => {
          successCallback("保存成功。");
          handleChange(User.convertUserInfo(user));
        })
        .catch(error => {
          errorCallback(get(error, "response.data.message", "保存失败。"));
        });
    },
    [user, handleChange]
  );

  const formFields = useMemo(
    () =>
      map(
        [
          {
            name: "code",
            title: "用户编码",
            type: "text",
            initialValue: user.code,
          },
          {
            name: "name",
            title: "名称",
            type: "text",
            initialValue: user.name,
          },
          {
            name: "email",
            title: "电子邮箱",
            type: "email",
            initialValue: user.email,
          },
          {
            name: "mobile",
            title: "手机",
            type: "number",
            initialValue: user.mobile,
          },
          {
            name: "menustyle_enum",
            required: false,
            title: "菜单风格",
            type: "select",
            options: menustyle_enums,
            initialValue: user.menustyle_enum,
            loading: isLoadingMenustyle,
            placeholder: isLoadingMenustyle ? "加载中..." : "",
          },
          {
                name: "orgunit_id",
                required: false,
                title: "部门",
                type: "select",
                options: orgunits,
                initialValue: user.orgunit_id,
                loading: isLoadingOrgunits,
                placeholder: isLoadingOrgunits ? "加载中..." : "",
              },
          !user.isDisabled && currentUser.id !== user.id
            ? {
                name: "group_ids",
                required: false,
                title: "权限组",
                type: "select",
                mode: "multiple",
                options: map(allGroups, group => ({name: group.name , value: group.id })),
                initialValue: user.groupIds,
                // options: map(allGroups, group => ({ name: group.name ==='admin' ? '管理员':(group.name ==='default' ? '起草':(group.name ==='audit' ? '审批':(group.name ==='draft' ? '提醒':(group.name ==='seal' ? '用印':(group.name ==='record' ? '备案':(group.name ==='user' ? '报表':(group.name ==='super_admin' ? '超级管理员':(group.name ==='lawyer' ? '律师':group.name)))))))), value: group.id })),
                // initialValue: map(groups, group => group.id),
                loading: isLoadingGroups,
                placeholder: isLoadingGroups ? "加载中..." : "",
              }
            : {
                name: "group_ids",
                title: "权限组",
                type: "content",
                required: false,
                content: isLoadingGroups ? "加载中..." : <UserGroups data-test="Groups" groups={groups} />,
              },
        ],
        field => ({ readOnly: user.isDisabled, required: true, ...field })
      ),
      [user, groups, allGroups, isLoadingGroups, orgunits, isLoadingOrgunits, menustyle_enums, isLoadingMenustyle]
  );

  return (
    <DynamicComponent name="UserProfile.UserInfoForm" {...props}>
      <DynamicForm fields={formFields} onSubmit={saveUser} hideSubmitButton={user.isDisabled} />
    </DynamicComponent>
  );
}

UserInfoForm.propTypes = {
  user: UserProfile.isRequired,
  onChange: PropTypes.func,
};

UserInfoForm.defaultProps = {
  onChange: () => {},
};
